package com.test.socket;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPEchoClientTimeout {

	private static final int TIMEOUT = 3000; // resend timeout(milliseconds)
	private static final int MAXIRIES = 5; // maximum retransmissions

	public static void main(String[] args) throws IOException {
		String[] argStrings = {};
		InetAddress serverAddress = InetAddress.getByName(argStrings[0]);// server
																			// address
		// convert the argument String to bytes using the default encoding
		byte[] bytesToSend = argStrings[1].getBytes();

		int servPort = (argStrings.length == 3) ? Integer
				.parseInt(argStrings[2]) : 7;
		DatagramSocket socket = new DatagramSocket();

		socket.setSoTimeout(TIMEOUT);// Maximum receive blocking
										// time(milliseconds)
		// send packet
		DatagramPacket sendPacket = new DatagramPacket(bytesToSend,
				bytesToSend.length, serverAddress, servPort);
		// receiving packet
		DatagramPacket receivePacket = new DatagramPacket(
				new byte[bytesToSend.length], bytesToSend.length);
		int tries =0; //packets may be lost , so we have to keeping trying
		boolean receivedResponse = false;
		do {
			socket.send(sendPacket);//attempt echo reply reception
			try {
				if(!receivePacket.getAddress().equals(serverAddress)){
					// check source 
					throw new IOException("Received packet from an unkown source");
				}
				receivedResponse =true;
			} catch (InterruptedIOException e) {//we did not get anything
				tries +=1;
				System.out.println("Time out, "+(MAXIRIES-tries)+" more tries...");
			}
			
		} while ((!receivedResponse)&&(tries<MAXIRIES));
		
		if(receivedResponse){
			System.out.println("Received: "+new String(receivePacket.getData()));
		}else{
			System.out.println("NO response -- giving up");
		}
		socket.close();
	}
}
